package com.huyn.baseframework.share;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.Toast;

import com.android.volley.Response;
import com.huyn.baseframework.model.WXLoginModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.VideoObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.LogUtil;
import com.sina.weibo.sdk.utils.Utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * Created by huyaonan on 16/8/8.
 */
public class WeiboUtil {

    private static WeiboUtil mInstance;

    /** 微博微博分享接口实例 */
    private IWeiboShareAPI mWeiboShareAPI = null;

    private Context context;

    private WeiboUtil(Activity context) {
        this.context = context;
        // 创建微博分享接口实例
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, WeiboConstants.APP_KEY);

        // 注册第三方应用到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
        // 但该附件栏集成分享权限需要合作申请，详情请查看 Demo 提示
        // NOTE：请务必提前注册，即界面初始化的时候或是应用程序初始化时，进行注册
        mWeiboShareAPI.registerApp();
    }

    public synchronized static WeiboUtil getInstance(Activity context) {
        if(mInstance == null)
            mInstance = new WeiboUtil(context);
        return mInstance;
    }

    public void authorize(final Context context, SsoHandler mSsoHandler, final Response.Listener<WXLoginModel> listener) {
        mSsoHandler.authorize(new WeiboAuthListener() {
            @Override
            public void onComplete(Bundle values) {
                // 从 Bundle 中解析 Token
                Oauth2AccessToken mAccessToken = Oauth2AccessToken.parseAccessToken(values);
                if (mAccessToken.isSessionValid()) {
                    // 保存 Token 到 SharedPreferences
                    AccessTokenKeeper.writeAccessToken(context, mAccessToken);
                    doWeiboLogin(context, mAccessToken, listener);
                } else {
                    // 以下几种情况，您会收到 Code：
                    // 1. 当您未在平台上注册的应用程序的包名与签名时；
                    // 2. 当您注册的应用程序包名与签名不正确时；
                    // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(context, "授权取消", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onWeiboException(WeiboException e) {
                e.printStackTrace();
                Toast.makeText(context, "微博登陆异常", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 微博登录并保留凭证
     */
    private void doWeiboLogin(Context context, Oauth2AccessToken mAccessToken, Response.Listener<WXLoginModel> listener) {
        HashMap<String, String> parameterMap = new HashMap<>();
        parameterMap.put("uid", mAccessToken.getUid());
        parameterMap.put("accessToken", mAccessToken.getToken());
        parameterMap.put(OpenApi.API_METHOD, OpenApi.WEIBO_LOGIN);
        BFJSONRequest request = new BFJSONRequest(WXLoginModel.class, parameterMap, listener);
        HttpRequestLoader.getInstance(context).startCacheLoader("", request, true);
    }

    /**
     * 检查微博的登陆状态是否过期,过期就清除
     * @param context
     */
    public static void checkAccessToken(Context context) {
        // 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息，
        // 第一次启动本应用，AccessToken 不可用
        Oauth2AccessToken mAccessToken = AccessTokenKeeper.readAccessToken(context);
        if (mAccessToken == null)
            return;
        //微博登陆失效了
        if (!mAccessToken.isSessionValid()) {
            //清除用户信息
            UserUtil.clearData(context);
        }
    }

    public void logout(Context context) {
        AccessTokenKeeper.clear(context);
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    public static TextObject getTextObj(String text) {
        TextObject textObject = new TextObject();
        textObject.text = text;
        return textObject;
    }

    /**
     * 创建图片消息对象。
     * @return 图片消息对象。
     */
    public static ImageObject getImageObj(String path, String content) {
        ImageObject imageObject = new ImageObject();
        imageObject.imagePath = path;
        imageObject.title = content;
//        imageObject.description = content;
        return imageObject;
    }

    /**
     * 创建图片消息对象。
     * @return 图片消息对象。
     */
    public static ImageObject getImageObj(Bitmap bitmap, String content) {
        ImageObject imageObject = new ImageObject();
        //设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        imageObject.setImageObject(bitmap);
        imageObject.title = content;
//        imageObject.description = content;
        return imageObject;
    }

    /**
     * 创建多媒体（网页）消息对象。
     * @return 多媒体（网页）消息对象。
     */
    public static WebpageObject getWebpageObj(String title, String desc, String url, Bitmap bitmap) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = desc;

        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = url;
//        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    public static VideoObject getVideoObj(String content, Bitmap bitmap, String url) {
        // 创建媒体消息
        VideoObject videoObject = new VideoObject();
        videoObject.identify = Utility.generateGUID();
        videoObject.title = content;
        videoObject.description = content;

        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, os);
            Utils.sysout("final size:" + os.toByteArray().length);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("Weibo.BaseMediaObject", "put thumb failed");
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //设置缩略图。最终压缩过的缩略图大小不得超过32kb。
        videoObject.setThumbImage(bitmap);
        videoObject.actionUrl = url;
        videoObject.dataUrl = "www.aube-tv.com";
        videoObject.dataHdUrl = "www.aube-tv.com";
        videoObject.duration = 10;
//        videoObject.defaultText = content;
        return videoObject;
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    public void sendMessage(Activity activity, BaseMediaObject content) {
        if (content == null) {
            Toast.makeText(activity, "分享内容为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
            sendSingleMessage(activity, content, null);
        } else {
            Toast.makeText(activity, "微博版本不支持", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    public void sendMessage(Activity activity, BaseMediaObject mediaObject, ShareModule content) {
        if (!mWeiboShareAPI.isWeiboAppInstalled()) {
            Toast.makeText(activity, "您还没有安装微博!", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (mShareType == SHARE_CLIENT) {
            if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
                if (supportApi >= 10351 /*ApiUtils.BUILD_INT_VER_2_2*/) {
                    sendMultiMessage(activity, mediaObject, content);
                } else {
                    sendSingleMessage(activity, mediaObject, content);
                }
            } else {
                Toast.makeText(activity, "微博版本不支持", Toast.LENGTH_SHORT).show();
            }
//        }
//        else if (mShareType == SHARE_ALL_IN_ONE) {
//            sendMultiMessage(hasText, hasImage, hasWebpage, hasMusic, hasVideo, hasVoice);
//        }
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 注意：当 {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 时，支持同时分享多条消息，
     * 同时可以分享文本、图片以及其它媒体资源（网页、音乐、视频、声音中的一种）。
     */
    private void sendMultiMessage(Activity activity, BaseMediaObject mediaObject, ShareModule content) {
        Utils.sysout("weibo sendMultiMessage");
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        if (content != null && StringUtils.isNotBlank(content.content)) {
            weiboMessage.textObject = getTextObj(content.content);
        }

        String type = "unknown";
        if (mediaObject instanceof ImageObject) {
            weiboMessage.imageObject = (ImageObject) mediaObject;
            type = "img";
        } else {
            if(mediaObject instanceof WebpageObject)
                type = "url";
            else if(mediaObject instanceof VideoObject)
                type = "video";
            weiboMessage.mediaObject = mediaObject;
        }

        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        if(content != null && StringUtils.isNotBlank(content.shareUrl))
            UmengUtils.reportUmengEvent(context, UmengUtils.SHARE_VIA_WEIBO, content.shareUrl);
        else
            UmengUtils.reportUmengEvent(context, UmengUtils.SHARE_VIA_WEIBO, type);

        // 3. 发送请求消息到微博，唤起微博分享界面
//        if (mShareType == SHARE_CLIENT) {
            mWeiboShareAPI.sendRequest(activity, request);
        Utils.sysout("weibo sendMultiMessage over:" + type);
//        }
//        else if (mShareType == SHARE_ALL_IN_ONE) {
//            AuthInfo authInfo = new AuthInfo(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
//            Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
//            String token = "";
//            if (accessToken != null) {
//                token = accessToken.getToken();
//            }
//            mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {
//
//                @Override
//                public void onWeiboException( WeiboException arg0 ) {
//                }
//
//                @Override
//                public void onComplete( Bundle bundle ) {
//                    Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                    AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
//                    Toast.makeText(getApplicationContext(), "onAuthorizeComplete token = " + newToken.getToken(), 0).show();
//                }
//
//                @Override
//                public void onCancel() {
//                }
//            });
//        }
    }

    private void sendSingleMessage(Activity context, BaseMediaObject content, ShareModule shareModule) {
        Utils.sysout("weibo sendSingleMessage");
        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();
        weiboMessage.mediaObject = content;

        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;

        String type = "unknown";
        if (content instanceof ImageObject) {
            type = "img";
        } else {
            if(content instanceof WebpageObject)
                type = "url";
            else if(content instanceof VideoObject)
                type = "video";
        }

        if(content != null && StringUtils.isNotBlank(shareModule.shareUrl))
            UmengUtils.reportUmengEvent(context, UmengUtils.SHARE_VIA_WEIBO, shareModule.shareUrl);
        else
            UmengUtils.reportUmengEvent(context, UmengUtils.SHARE_VIA_WEIBO, type);

        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest(context, request);
    }

    public void startShareVideo(Activity activity, ShareModule content) {
        sendMessage(activity, getVideoObj(content.content, content.imgBm, content.shareUrl), content);
    }

    public void startShareImg(Activity activity, ShareModule content) {
        if(content.imgBm != null) {
            Utils.sysout("weibo share pic by bitmap");
            sendMessage(activity, getImageObj(content.imgBm, content.content), content);
        } else if(StringUtils.isNotBlank(content.imagePath)) {
            Utils.sysout("weibo share pic by imagePath");
            sendMessage(activity, getImageObj(content.imagePath, content.content), content);
        } else
            Utils.showToast(activity, "分享图片为空");
    }

    /**
     * 分享来自ShareUtil
     * @param context
     * @param content
     */
    public void startShare(Context context, ShareModule content) {
        sendMessage((Activity) context, getWebpageObj(content.title, content.content, content.shareUrl, content.imgBm), content);
    }

}
